package ${packageName}.core;

import java.sql.Connection;
import java.sql.SQLException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import ${packageName}.common.DaoException;

/**
 * 
 * 事务管理器
 * 
 * @author 00fly
 * @version [版本号, ${date?date}]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
public class TransactionManager
{
    private Logger log = LoggerFactory.getLogger(this.getClass());
    
    private MySqlDBUtil dbUtil = MySqlDBUtil.getInstance();
    
    private Connection conn;
    
    /**
     * <默认构造函数>
     */
    protected TransactionManager(Connection conn)
    {
        this.conn = conn;
    }
    
    /**
     * 开启事务
     * 
     * @throws DaoException
     */
    public void beginTransaction()
        throws DaoException
    {
        log.info("------开启事务-------");
        try
        {
            conn.setAutoCommit(false); // 把事务提交方式改为手工提交
        }
        catch (SQLException e)
        {
            log.error(e.getMessage());
            throw new DaoException("开启事务时出现异常", e);
        }
    }
    
    /**
     * 提交事务并关闭连接
     * 
     * @throws DaoException
     */
    public void commitAndClose()
        throws DaoException
    {
        log.info("------提交事务-------");
        try
        {
            conn.commit(); // 提交事务
        }
        catch (SQLException e)
        {
            log.error(e.getMessage());
            throw new DaoException("提交事务时出现异常", e);
        }
        finally
        {
            dbUtil.close(conn);
        }
    }
    
    /**
     * 回滚事务并关闭连接
     * 
     * @throws DaoException
     */
    public void rollbackAndClose()
        throws DaoException
    {
        log.info("------ 系统异常，回滚事务-------");
        try
        {
            conn.rollback();
        }
        catch (SQLException e)
        {
            log.error(e.getMessage());
            throw new DaoException("回滚事务时出现异常", e);
        }
        finally
        {
            dbUtil.close(conn);
        }
    }
}
